#include <iostream>
#include "net_camera.h"
#include "frame_state_callback.h"
#include "frame_config.h"
#include "camera_kit.h"

using namespace std;
using namespace OHOS::Media;

NetCamera *NetCamera::m_instance = nullptr;

const int DEFAULT_NET_CAMERA_PORT = 15000;

NetCamera *NetCamera::GetInstance(void)
{
    if (m_instance == nullptr)
    {
        m_instance = new NetCamera(DEFAULT_NET_CAMERA_PORT);
    }
    return m_instance;
}

string GetCameraID(void) {
    list<string> camList = CameraKit::GetInstance()->GetCameraIds();
    for (auto &cam : camList) {
        cout << "camera name:" << cam << endl;
        const CameraAbility *ability = CameraKit::GetInstance()->GetCameraAbility(cam);
        /* find camera which fits user's ability */
        list<CameraPicSize> sizeList = ability->GetSupportedSizes(0);
        if (find(sizeList.begin(), sizeList.end(), CAM_PIC_1080P) != sizeList.end()) {
            return cam;
        }
    }
    return "";
}

void NetCamera::OnCreated(Camera& camera) {
    cout << "Sample recv OnCreate camera." << endl;
    auto config = CameraConfig::CreateCameraConfig();
    config->SetFrameStateCallback((FrameStateCallback*)this, &m_eventHdlr);
    camera.Configure(*config);
    m_camera = &camera;
}

int32_t NetCamera::InitCamera(void) {
    string cameraID = GetCameraID();

    CameraKit::GetInstance()->CreateCamera(cameraID, *this, m_eventHdlr);

    FrameConfig *fc = new FrameConfig(FRAME_CONFIG_RECORD);

    return 0;
}


int32_t NetCamera::Run(int portID)
{
    if (m_instance != nullptr)
    {
        printf("instance already running");
        return -1;
    }

    m_instance = new NetCamera(portID);

    m_instance->InitCamera();

    // NET Server init here
    m_instance->Shutdown();

    delete m_instance;
    m_instance = nullptr;
    return 0;
}

int32_t NetCamera::Shutdown(void) {
    // TODO :shutdown NetCamera
    return 0;
}
